<template>
  <view class="container">
    <!-- 收货地址 -->
    <view class="address-section" @tap="goAddressList">
      <view class="address-info" v-if="address">
        <view class="user-info">
          <text class="name">{{address.name}}</text>
          <text class="phone">{{address.phone}}</text>
        </view>
        <view class="address">{{address.province}}{{address.city}}{{address.district}}{{address.detail}}</view>
      </view>
      <view class="no-address" v-else>
        <text>请选择收货地址</text>
        <text class="iconfont icon-arrow-right"></text>
      </view>
    </view>
    
    <!-- 商品信息 -->
    <view class="product-section">
      <view class="product-item" v-for="(item, index) in productList" :key="index">
        <image :src="item.image" mode="aspectFill"></image>
        <view class="product-info">
          <text class="title">{{item.title}}</text>
          <text class="specs">{{item.specs}}</text>
          <view class="price-wrap">
            <text class="price">¥{{item.price}}</text>
            <text class="quantity">x{{item.quantity}}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 优惠券 -->
    <view class="coupon-section" @tap="showCouponPopup">
      <text>优惠券</text>
      <view class="right">
        <text class="coupon-info" v-if="selectedCoupon">已选择{{selectedCoupon.name}}</text>
        <text class="iconfont icon-arrow-right"></text>
      </view>
    </view>
    
    <!-- 订单备注 -->
    <view class="remark-section">
      <text>订单备注</text>
      <input type="text" v-model="remark" placeholder="请输入订单备注" />
    </view>
    
    <!-- 金额信息 -->
    <view class="amount-section">
      <view class="amount-item">
        <text>商品总额</text>
        <text>¥{{totalAmount}}</text>
      </view>
      <view class="amount-item">
        <text>优惠金额</text>
        <text class="discount">-¥{{discountAmount}}</text>
      </view>
      <view class="amount-item">
        <text>运费</text>
        <text>¥{{freight}}</text>
      </view>
      <view class="amount-item total">
        <text>实付金额</text>
        <text class="price">¥{{actualAmount}}</text>
      </view>
    </view>
    
    <!-- 底部提交栏 -->
    <view class="submit-bar">
      <view class="total">
        <text>合计：</text>
        <text class="price">¥{{actualAmount}}</text>
      </view>
      <button class="submit-btn" @tap="submitOrder">提交订单</button>
    </view>
    
    <!-- 优惠券选择弹窗 -->
    <uni-popup ref="couponPopup" type="bottom">
      <view class="coupon-popup">
        <view class="popup-header">
          <text>选择优惠券</text>
          <text class="close" @tap="closeCouponPopup">×</text>
        </view>
        <view class="popup-content">
          <view class="coupon-list">
            <view 
              class="coupon-item" 
              v-for="(item, index) in couponList" 
              :key="index"
              :class="{ active: selectedCoupon && selectedCoupon.id === item.id }"
              @tap="selectCoupon(item)"
            >
              <view class="left">
                <text class="amount">¥{{item.amount}}</text>
                <text class="condition">满{{item.condition}}可用</text>
              </view>
              <view class="right">
                <text class="name">{{item.name}}</text>
                <text class="validity">有效期至：{{item.validity}}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" @tap="confirmCoupon">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { userApi, orderApi, couponApi } from '@/api/index'
import { showToast } from '@/utils/common'

export default {
  data() {
    return {
      address: null,
      productList: [],
      couponList: [],
      selectedCoupon: null,
      remark: '',
      freight: 0
    }
  },
  computed: {
    totalAmount() {
      return this.productList.reduce((total, item) => {
        return total + parseFloat(item.price) * item.quantity
      }, 0).toFixed(2)
    },
    discountAmount() {
      if (!this.selectedCoupon) return '0.00'
      return this.selectedCoupon.amount
    },
    actualAmount() {
      const total = parseFloat(this.totalAmount)
      const discount = parseFloat(this.discountAmount)
      const freight = parseFloat(this.freight)
      return (total - discount + freight).toFixed(2)
    }
  },
  onLoad(options) {
    // 获取商品信息
    if (options.productId) {
      // 从商品详情页跳转
      this.getProductInfo(options.productId, options.specs, options.quantity)
    } else if (options.items) {
      // 从购物车跳转
      this.getCartItems(JSON.parse(options.items))
    }
    
    // 获取收货地址
    this.getAddressList()
    
    // 获取优惠券列表
    this.getCouponList()
  },
  methods: {
    // 获取商品信息
    async getProductInfo(id, specs, quantity) {
      try {
        const res = await productApi.getProductDetail(id)
        this.productList = [{
          id: res.id,
          title: res.title,
          price: res.price,
          image: res.images[0],
          specs: Object.values(JSON.parse(specs)).join('，'),
          quantity: parseInt(quantity)
        }]
      } catch (error) {
        showToast('商品信息加载失败')
      }
    },
    
    // 获取购物车商品
    async getCartItems(items) {
      try {
        const res = await cartApi.getCartList()
        this.productList = res.filter(item => 
          items.some(selected => selected.id === item.id)
        ).map(item => {
          const selected = items.find(selected => selected.id === item.id)
          return {
            ...item,
            quantity: selected.quantity
          }
        })
      } catch (error) {
        showToast('商品信息加载失败')
      }
    },
    
    // 获取收货地址列表
    async getAddressList() {
      try {
        const res = await userApi.getAddressList()
        this.address = res.find(item => item.isDefault) || res[0] || null
      } catch (error) {
        showToast('收货地址加载失败')
      }
    },
    
    // 获取优惠券列表
    async getCouponList() {
      try {
        const res = await couponApi.getMyCoupons()
        this.couponList = res.filter(item => 
          parseFloat(item.condition) <= parseFloat(this.totalAmount)
        )
      } catch (error) {
        showToast('优惠券加载失败')
      }
    },
    
    // 跳转收货地址列表
    goAddressList() {
      uni.navigateTo({
        url: '/pages/address/list'
      })
    },
    
    // 显示优惠券选择弹窗
    showCouponPopup() {
      this.$refs.couponPopup.open()
    },
    
    // 关闭优惠券选择弹窗
    closeCouponPopup() {
      this.$refs.couponPopup.close()
    },
    
    // 选择优惠券
    selectCoupon(coupon) {
      this.selectedCoupon = coupon
    },
    
    // 确认优惠券选择
    confirmCoupon() {
      this.closeCouponPopup()
    },
    
    // 提交订单
    async submitOrder() {
      if (!this.address) {
        showToast('请选择收货地址')
        return
      }
      
      try {
        const data = {
          addressId: this.address.id,
          products: this.productList.map(item => ({
            id: item.id,
            quantity: item.quantity
          })),
          couponId: this.selectedCoupon ? this.selectedCoupon.id : null,
          remark: this.remark,
          amount: this.actualAmount
        }
        
        const res = await orderApi.createOrder(data)
        
        // 跳转到支付页面
        uni.navigateTo({
          url: `/pages/payment/index?orderId=${res.id}`
        })
      } catch (error) {
        showToast('订单提交失败')
      }
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120rpx;
}

.address-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .address-info {
    .user-info {
      margin-bottom: 10rpx;
      
      .name {
        font-size: 32rpx;
        color: #333;
        margin-right: 20rpx;
      }
      
      .phone {
        font-size: 28rpx;
        color: #666;
      }
    }
    
    .address {
      font-size: 28rpx;
      color: #666;
    }
  }
  
  .no-address {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    text {
      font-size: 28rpx;
      color: #666;
      
      &.icon-arrow-right {
        color: #999;
      }
    }
  }
}

.product-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .product-item {
    display: flex;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
    }
    
    .product-info {
      flex: 1;
      
      .title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .specs {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 10rpx;
      }
      
      .price-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .price {
          font-size: 32rpx;
          color: #ff0000;
        }
        
        .quantity {
          font-size: 28rpx;
          color: #999;
        }
      }
    }
  }
}

.coupon-section {
  background: #fff;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  
  text {
    font-size: 28rpx;
    color: #333;
    
    &.coupon-info {
      color: #ff0000;
      margin-right: 10rpx;
    }
    
    &.icon-arrow-right {
      color: #999;
    }
  }
}

.remark-section {
  background: #fff;
  padding: 30rpx;
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  
  text {
    font-size: 28rpx;
    color: #333;
    margin-right: 20rpx;
  }
  
  input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
}

.amount-section {
  background: #fff;
  padding: 30rpx;
  
  .amount-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    text {
      font-size: 28rpx;
      color: #666;
      
      &.discount {
        color: #ff0000;
      }
      
      &.price {
        font-size: 36rpx;
        color: #ff0000;
        font-weight: bold;
      }
    }
    
    &.total {
      margin-top: 20rpx;
      padding-top: 20rpx;
      border-top: 1rpx solid #f5f5f5;
    }
  }
}

.submit-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  
  .total {
    flex: 1;
    
    text {
      font-size: 28rpx;
      color: #333;
      
      &.price {
        font-size: 36rpx;
        color: #ff0000;
        font-weight: bold;
      }
    }
  }
  
  .submit-btn {
    width: 240rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: #ff0000;
    color: #fff;
    border-radius: 40rpx;
    margin-left: 30rpx;
    font-size: 28rpx;
  }
}

.coupon-popup {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    text {
      font-size: 32rpx;
      color: #333;
      
      &.close {
        font-size: 40rpx;
        color: #999;
      }
    }
  }
  
  .popup-content {
    padding: 30rpx;
    max-height: 60vh;
    overflow-y: auto;
    
    .coupon-list {
      .coupon-item {
        display: flex;
        padding: 20rpx;
        background: #f5f5f5;
        border-radius: 8rpx;
        margin-bottom: 20rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        &.active {
          background: #fff0f0;
          border: 1rpx solid #ff0000;
        }
        
        .left {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding-right: 20rpx;
          border-right: 1rpx dashed #ddd;
          
          .amount {
            font-size: 40rpx;
            color: #ff0000;
            font-weight: bold;
            margin-bottom: 10rpx;
          }
          
          .condition {
            font-size: 24rpx;
            color: #999;
          }
        }
        
        .right {
          flex: 1;
          padding-left: 20rpx;
          
          .name {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 10rpx;
            display: block;
          }
          
          .validity {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }
  }
  
  .popup-footer {
    padding: 30rpx;
    border-top: 1rpx solid #f5f5f5;
    
    .confirm-btn {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background: #ff0000;
      color: #fff;
      border-radius: 40rpx;
      font-size: 28rpx;
    }
  }
}
</style> 